package com.xiaoyun.xymall.product.exception;

import com.xiaoyun.common.exception.BizCodeEnume;
import com.xiaoyun.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.xiaoyun.xymall.product.controller")
public class XymallExceptionControllerAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("數據校驗出現問題：{},異常類型：{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            String message = item.getDefaultMessage();
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleValidException(Throwable e) {
        log.error("系统异常：{}", e.getMessage());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION);
    }
}
